﻿using AutoMapper;
using HamcoWcs.Contract.ContractCommon;
using HamcoWcs.DAL;
using HamcoWcs.Entitys.DeviceMsgQueues;
using HamcoWcs.Models.Common;
using HamcoWcs.Models.Common.Enums;
using HamcoWcs.Models.DeviceMsgQueues;
using HamcoWcs.Models.DeviceMsgs;
using HamcoWcs.Models.Devices;
using HamcoWcs.Service.Common;
using Microsoft.EntityFrameworkCore;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace HamcoWcs.Workers.RouteWorkers
{
    /// <summary>路径后台服务</summary>
    [DisallowConcurrentExecution]
    public class RouteWorker : WorkerBase
    {

        public override Task Execute(IJobExecutionContext context)
        {
            // 检查Error Node ，true:更新路径


            try
            {
#if DEBUG
                //ASRSInitFlag = true;
#endif
                #region [长巷道切单切换路径]

                bool transportFlag = GetTransportFlag();

                // 满足自动切方向条件
                if (transportFlag)
                {
                    AutoChangeMode();
                    AutoChangeDestination();
                }
                DownAutoChangeRoute();

                _wcsDbContext.SaveChanges();

                #endregion


                //_pathService.CalcRoute();
            }
            catch (Exception ex)
            {
                _logger.AddSystemErrorLog($"RouteWorker:{ex.Message}");
            }
            return Task.CompletedTask;
        }

        /// <summary>
        /// 设备初始完成
        /// </summary>
        public static bool ASRSInitFlag { get; set; } = false;
        private static bool AllowChangeRouteFlag { get; set; } = false;
        private static int TimeThreshold { get; set; } = 30 * 60;


        /// <summary>
        /// 设备宕机切换路径，1和2都宕机则无可用路径<br/>
        /// <br/>
        /// 1. ErrorFlag1 : CJMIFB00,CJVCVB00宕机时，切换CJVCV800方向为出库，卡控搬送任务<br/>
        /// 2. ErrorFlag2 : CJMIFC00,CJVCVC00宕机时，切换CJVCV700方向为入库，卡控搬送任务<br/>
        /// 3. ErrorFlag3 : CJVCV400,CJVCV500宕机时，长库上楼切换到短库搬送<br/>
        /// 4. ErrorFlag4 : CJVCV300,CJVCV600宕机时，成品入长库先走短库<br/>
        /// 5. ErrorFlag5 : CJRGV200宕机时长库都切换到短库中转
        /// 6. ErrorFlag6 : CJVCV700宕机时，短库上楼切换到长库搬送<br/>
        /// 7. ErrorFlag7 : CJVCV800宕机时，成品入短库先走长库<br/>
        /// </summary>
        private void DownAutoChangeRoute()
        {
            // 未初始完成不开始自动切换路径
            if (!ASRSInitFlag) return;

            #region [获取异常信息]

            bool errorFlag1 = false;
            bool errorFlag2 = false;
            bool errorFlag3 = false;
            bool errorFlag4 = false;
            bool errorFlag5 = false;
            bool errorFlag6 = false;
            bool errorFlag7 = false;

            foreach (var node in _asrs.Nodes)
            {
                string nn = node.NodeName;
                if (GlobalValue.RouteNeedChangeRouteNode.Contains(nn))
                {
                    bool s = node.MachineState == EnumMachineState.DOWN;
                    if (nn == "CJMIFB00" || nn == "CJVCVB00")
                        errorFlag1 |= s;
                    if (nn == "CJMIFC00" || nn == "CJVCVC00")
                        errorFlag2 |= s;
                    if (nn == "CJVCV400" || nn == "CJVCV500")
                        errorFlag3 |= s;
                    if (nn == "CJVCV300" || nn == "CJVCV600")
                        errorFlag4 |= s;
                    if (nn == "CJRGV200")
                        errorFlag5 |= s;
                    if (nn == "CJVCV700")
                        errorFlag6 |= s;
                    if (nn == "CJVCV800")
                        errorFlag7 |= s;
                }
            }

            #endregion

            #region [设置或清零异常时间]

            int errorTime1 = 0;
            int errorTime2 = 0;
            int errorTime3 = 0;
            int errorTime4 = 0;
            int errorTime5 = 0;
            int errorTime6 = 0;
            int errorTime7 = 0;

            if (errorFlag1)
            {
                var t = int.TryParse(_config.GetConfigValue("MACHINEDOWNTIME1"), out int t1);
                if (t) t1++; else t1 = 1;
                errorTime1 = t1;
                _config.SetConfigMsg("MACHINEDOWNTIME1", t1.ToString());
            }
            else
            {
                _config.SetConfigMsg("MACHINEDOWNTIME1", "0");
                errorTime1 = 0;
            }

            if (errorFlag2)
            {
                var t = int.TryParse(_config.GetConfigValue("MACHINEDOWNTIME2"), out int t1);
                if (t) t1++; else t1 = 1;
                errorTime2 = t1;
                _config.SetConfigMsg("MACHINEDOWNTIME2", t1.ToString());
            }
            else
            {
                _config.SetConfigMsg("MACHINEDOWNTIME2", "0");
                errorTime2 = 0;
            }

            if (errorFlag3)
            {
                var t = int.TryParse(_config.GetConfigValue("MACHINEDOWNTIME3"), out int t1);
                if (t) t1++; else t1 = 1;
                errorTime3 = t1;
                _config.SetConfigMsg("MACHINEDOWNTIME3", t1.ToString());
            }
            else
            {
                _config.SetConfigMsg("MACHINEDOWNTIME3", "0");
                errorTime3 = 0;
            }

            if (errorFlag4)
            {
                var t = int.TryParse(_config.GetConfigValue("MACHINEDOWNTIME4"), out int t1);
                if (t) t1++; else t1 = 1;
                errorTime4 = t1;
                _config.SetConfigMsg("MACHINEDOWNTIME4", t1.ToString());
            }
            else
            {
                _config.SetConfigMsg("MACHINEDOWNTIME4", "0");
                errorTime4 = 0;
            }

            if (errorFlag5)
            {
                var t = int.TryParse(_config.GetConfigValue("MACHINEDOWNTIME5"), out int t1);
                if (t) t1++; else t1 = 1;
                errorTime5 = t1;
                _config.SetConfigMsg("MACHINEDOWNTIME5", t1.ToString());
            }
            else
            {
                _config.SetConfigMsg("MACHINEDOWNTIME5", "0");
                errorTime5 = 0;
            }

            if (errorFlag6)
            {
                var t = int.TryParse(_config.GetConfigValue("MACHINEDOWNTIME6"), out int t1);
                if (t) t1++; else t1 = 1;
                errorTime6 = t1;
                _config.SetConfigMsg("MACHINEDOWNTIME6", t1.ToString());
            }
            else
            {
                _config.SetConfigMsg("MACHINEDOWNTIME6", "0");
                errorTime6 = 0;
            }

            if (errorFlag7)
            {
                var t = int.TryParse(_config.GetConfigValue("MACHINEDOWNTIME7"), out int t1);
                if (t) t1++; else t1 = 1;
                errorTime7 = t1;
                _config.SetConfigMsg("MACHINEDOWNTIME7", t1.ToString());
            }
            else
            {
                _config.SetConfigMsg("MACHINEDOWNTIME7", "0");
                errorTime7 = 0;
            }

            #endregion

            // 获取切换路径时间阈值
            TimeThreshold = int.Parse(_config.GetConfigValue("MACHINEDOWNTHRESHOLD"));
            // 获取自动切换路径允许信号
            AllowChangeRouteFlag = _config.GetConfigValue("MACHINEDOWNALLOWREROUTEFLAG") == "1";
            // 不允许宕机切换路径时退出
            if (!AllowChangeRouteFlag) return;

            GlobalValue.ErrorFlag1 = errorTime1 > TimeThreshold;
            GlobalValue.ErrorFlag2 = errorTime2 > TimeThreshold;
            GlobalValue.ErrorFlag3 = errorTime3 > TimeThreshold;
            GlobalValue.ErrorFlag4 = errorTime4 > TimeThreshold;
            GlobalValue.ErrorFlag5 = errorTime5 > TimeThreshold;
            GlobalValue.ErrorFlag6 = errorTime6 > TimeThreshold;
            GlobalValue.ErrorFlag7 = errorTime7 > TimeThreshold;


            var paths = _pathService.GetAllPath();
            // 1. CJMIFB00,CJVCVB00宕机时，切换CJVCV800方向为出库，卡控搬送任务<br/>
            if (GlobalValue.ErrorFlag1 && (GlobalValue.ErrorFlag1 != GlobalValue.ErrorFlag2))
            {
                foreach (var path in paths.Values)
                {
                    // 成品入库
                    if (path.FromNode.Contains("CJMCV") && path.ToNode.Contains("CJSTW"))
                    {
                        if (path.ToNode == "CJSTW100")
                        {
                            var p = $"{path.FromNode}-CJVCVC00-CJMIFC00-CJVCV600-CJVCV300-CJVCV200-{path.ToNode}";
                            if (path.UsedPath != p)
                            {
                                path.UsedPath = p;
                                _pathService.ReRoutePathEdges(path.PathName);
                            }
                        }
                        else
                        {
                            var p = $"{path.FromNode}-CJVCVC00-CJMIFC00-CJVCV600-CJVCV300-{path.ToNode}";
                            if (path.UsedPath != p)
                            {
                                path.UsedPath = p;
                                _pathService.ReRoutePathEdges(path.PathName);
                            }
                        }
                    }
                    // 空包上楼
                    if (path.FromNode.Contains("CJSTW") && path.ToNode.Contains("CJMCV"))
                    {
                        if (path.FromNode == "CJSTW100")
                        {
                            var p = $"{path.FromNode}-CJVCV800-CJMIFC00-CJVCVC00-{path.ToNode}";
                            if (path.UsedPath != p)
                            {
                                path.UsedPath = p;
                                _pathService.ReRoutePathEdges(path.PathName);
                            }
                        }
                        else
                        {
                            var p = $"{path.FromNode}-CJVCV200-CJVCV800-CJMIFC00-CJVCVC00-{path.ToNode}";
                            if (path.UsedPath != p)
                            {
                                path.UsedPath = p;
                                _pathService.ReRoutePathEdges(path.PathName);
                            }
                        }
                    }
                }

                var vcv800 = _asrs.Pcons.FirstOrDefault(x => x.MachineName == "CJVCV800" && x.PortName == "01");
                // VCV800要切换从出库模式
                if (vcv800.WorkType == 1)
                {
                    bool isGoods = vcv800.Machine.Pcons.Any(x => x.IsGoods == 1 || !string.IsNullOrEmpty(x.UnitId));
                    bool isTask = _wcsDbContext.SubTasks.Any(x => x.ToLoc == "CJVCV800" && x.TaskStatus == EnumSubTaskStatus.OnProgress.ToString());

                    if (!isGoods && !isTask)
                    {
                        var pconMsg = new PconSendMsg()
                        {
                            PconName = (ushort)vcv800.PconName,
                            Request = (ushort)EnumPconSendMsg.ChangeOutModeCmd
                        };
                        var deviceMsgQueueDto = new DeviceMsgQueueDto(vcv800, pconMsg);

                        var deviceMsgQueue = _mapper.Map<DeviceMsgQueue>(deviceMsgQueueDto);
                        _wcsDbContext.Add(deviceMsgQueue);
                        _wcsDbContext.SaveChanges();
                    }
                }
            }
            else
            {
                var vcv800 = _asrs.Pcons.FirstOrDefault(x => x.MachineName == "CJVCV800" && x.PortName == "01");
                // 恢复时VCV800要切换从入库模式
                if (vcv800.WorkType == 2)
                {
                    bool isGoods = vcv800.Machine.Pcons.Any(x => x.IsGoods == 1 || !string.IsNullOrEmpty(x.UnitId));
                    bool isTask = _wcsDbContext.SubTasks.Any(x => x.ToLoc == "CJVCV800" && x.TaskStatus == EnumSubTaskStatus.OnProgress.ToString());

                    if (!isGoods && !isTask)
                    {
                        var pconMsg = new PconSendMsg()
                        {
                            PconName = (ushort)vcv800.PconName,
                            Request = (ushort)EnumPconSendMsg.ChangeInModeCmd
                        };
                        var deviceMsgQueueDto = new DeviceMsgQueueDto(vcv800, pconMsg);

                        var deviceMsgQueue = _mapper.Map<DeviceMsgQueue>(deviceMsgQueueDto);
                        _wcsDbContext.Add(deviceMsgQueue);
                        _wcsDbContext.SaveChanges();
                    }
                }
            }
            // 2. CJMIFC00,CJVCVC00宕机时，切换CJVCV700方向为入库，卡控搬送任务<br/>
            if (GlobalValue.ErrorFlag2 && (GlobalValue.ErrorFlag1 != GlobalValue.ErrorFlag2))
            {
                foreach (var path in paths.Values)
                {
                    // 成品入库
                    if (path.FromNode.Contains("CJMCV") && path.ToNode.Contains("CJSTW"))
                    {
                        if (path.ToNode == "CJSTW100")
                        {
                            var p = $"{path.FromNode}-CJVCVB00-CJMIFB00-CJVCV700-{path.ToNode}";
                            if (path.UsedPath != p)
                            {
                                path.UsedPath = p;
                                _pathService.ReRoutePathEdges(path.PathName);
                            }
                        }
                        else
                        {
                            var p = $"{path.FromNode}-CJVCVB00-CJMIFB00-CJVCV700-CJVCV200-{path.ToNode}";
                            if (path.UsedPath != p)
                            {
                                path.UsedPath = p;
                                _pathService.ReRoutePathEdges(path.PathName);
                            }
                        }
                    }
                    // 空包上楼
                    if (path.FromNode.Contains("CJSTW") && path.ToNode.Contains("CJMCV"))
                    {
                        if (path.FromNode == "CJSTW100")
                        {
                            var p = $"{path.FromNode}-CJVCV200-CJVCV400-CJVCV500-CJMIFB00-CJVCVB00-{path.ToNode}";
                            if (path.UsedPath != p)
                            {
                                path.UsedPath = p;
                                _pathService.ReRoutePathEdges(path.PathName);
                            }
                        }
                        else
                        {
                            var p = $"{path.FromNode}-CJVCV400-CJVCV500-CJMIFB00-CJVCVB00-{path.ToNode}";
                            if (path.UsedPath != p)
                            {
                                path.UsedPath = p;
                                _pathService.ReRoutePathEdges(path.PathName);
                            }
                        }
                    }
                }
                var vcv700 = _asrs.Pcons.FirstOrDefault(x => x.MachineName == "CJVCV700" && x.PortName == "01");
                // VCV700要切换从入库模式
                if (vcv700.WorkType == 2)
                {
                    bool isGoods = vcv700.Machine.Pcons.Any(x => x.IsGoods == 1 || !string.IsNullOrEmpty(x.UnitId));
                    bool isTask = _wcsDbContext.SubTasks.Any(x => x.ToLoc == "CJVCV700" && x.TaskStatus == EnumSubTaskStatus.OnProgress.ToString());

                    if (!isGoods && !isTask)
                    {
                        var pconMsg = new PconSendMsg()
                        {
                            PconName = (ushort)vcv700.PconName,
                            Request = (ushort)EnumPconSendMsg.ChangeInModeCmd
                        };
                        var deviceMsgQueueDto = new DeviceMsgQueueDto(vcv700, pconMsg);

                        var deviceMsgQueue = _mapper.Map<DeviceMsgQueue>(deviceMsgQueueDto);
                        _wcsDbContext.Add(deviceMsgQueue);
                        _wcsDbContext.SaveChanges();
                    }
                }
            }
            else
            {
                var vcv700 = _asrs.Pcons.FirstOrDefault(x => x.MachineName == "CJVCV700" && x.PortName == "01");
                // 恢复时VCV700要切换从出库模式
                if (vcv700.WorkType == 1)
                {
                    bool isGoods = vcv700.Machine.Pcons.Any(x => x.IsGoods == 1 || !string.IsNullOrEmpty(x.UnitId));
                    bool isTask = _wcsDbContext.SubTasks.Any(x => x.ToLoc == "CJVCV700" && x.TaskStatus == EnumSubTaskStatus.OnProgress.ToString());

                    if (!isGoods && !isTask)
                    {
                        var pconMsg = new PconSendMsg()
                        {
                            PconName = (ushort)vcv700.PconName,
                            Request = (ushort)EnumPconSendMsg.ChangeOutModeCmd
                        };
                        var deviceMsgQueueDto = new DeviceMsgQueueDto(vcv700, pconMsg);

                        var deviceMsgQueue = _mapper.Map<DeviceMsgQueue>(deviceMsgQueueDto);
                        _wcsDbContext.Add(deviceMsgQueue);
                        _wcsDbContext.SaveChanges();
                    }
                }
            }

            // 当提升机正常时候，触发下面的条件
            if (!(GlobalValue.ErrorFlag1 && (GlobalValue.ErrorFlag1 != GlobalValue.ErrorFlag2)) && !(GlobalValue.ErrorFlag2 && (GlobalValue.ErrorFlag1 != GlobalValue.ErrorFlag2)))
            {
                // 3. CJVCV400,CJVCV500宕机时，长库上楼切换到短库搬送<br/>
                if (GlobalValue.ErrorFlag3 && !GlobalValue.ErrorFlag5)
                {
                    foreach (var path in paths.Values)
                    {
                        // CJSTW200空包上楼
                        if (path.FromNode.Contains("CJSTW200") && path.ToNode.Contains("CJMCV"))
                        {
                            var p = $"{path.FromNode}-CJVCV200-CJVCV700-CJMIFB00-CJVCVB00-{path.ToNode}";
                            if (path.UsedPath != p)
                            {
                                path.UsedPath = p;
                                _pathService.ReRoutePathEdges(path.PathName);
                            }
                        }
                    }
                }
                // 4. CJVCV300,CJVCV600宕机时，成品入长库先走短库<br/>
                if (GlobalValue.ErrorFlag4 && !GlobalValue.ErrorFlag5)
                {
                    foreach (var path in paths.Values)
                    {
                        // CJSTW200成品入库
                        if (path.FromNode.Contains("CJMCV") && path.ToNode.Contains("CJSTW200"))
                        {
                            var p = $"{path.FromNode}-CJVCVC00-CJMIFC00-CJVCV800-CJVCV200-{path.ToNode}";
                            if (path.UsedPath != p)
                            {
                                path.UsedPath = p;
                                _pathService.ReRoutePathEdges(path.PathName);
                            }
                        }
                    }
                }
                // 5. CJRGV200宕机时长库都切换到短库中转
                if (GlobalValue.ErrorFlag5)
                {
                    foreach (var path in paths.Values)
                    {
                        // CJSTW200空包上楼
                        if (path.FromNode.Contains("CJSTW200") && path.ToNode.Contains("CJMCV"))
                        {
                            var p = $"{path.FromNode}-CJVCV200-CJVCV700-CJMIFB00-CJVCVB00-{path.ToNode}";
                            if (path.UsedPath != p)
                            {
                                path.UsedPath = p;
                                _pathService.ReRoutePathEdges(path.PathName);
                            }
                        }
                        // CJSTW200成品入库
                        if (path.FromNode.Contains("CJMCV") && path.ToNode.Contains("CJSTW200"))
                        {
                            var p = $"{path.FromNode}-CJVCVC00-CJMIFC00-CJVCV800-CJVCV200-{path.ToNode}";
                            if (path.UsedPath != p)
                            {
                                path.UsedPath = p;
                                _pathService.ReRoutePathEdges(path.PathName);
                            }
                        }
                    }
                }
                // 6. CJVCV700宕机时，短库上楼切换到长库搬送<br/>
                if (GlobalValue.ErrorFlag6 && !(GlobalValue.ErrorFlag5 || GlobalValue.ErrorFlag3))
                {
                    foreach (var path in paths.Values)
                    {
                        // CJSTW100空包上楼
                        if (path.FromNode.Contains("CJSTW100") && path.ToNode.Contains("CJMCV"))
                        {
                            var p = $"{path.FromNode}-CJVCV200-CJVCV400-CJVCV500-CJMIFB00-CJVCVB00-{path.ToNode}";
                            if (path.UsedPath != p)
                            {
                                path.UsedPath = p;
                                _pathService.ReRoutePathEdges(path.PathName);
                            }
                        }
                    }
                }
                // 7. CJVCV800宕机时，成品入短库先走长库<br/>
                if (GlobalValue.ErrorFlag7 && !(GlobalValue.ErrorFlag5 || GlobalValue.ErrorFlag4))
                {
                    foreach (var path in paths.Values)
                    {
                        // CJSTW100成品入库
                        if (path.FromNode.Contains("CJMCV") && path.ToNode.Contains("CJSTW100"))
                        {
                            var p = $"{path.FromNode}-CJVCVC00-CJMIFC00-CJVCV600-CJVCV300-CJVCV200-{path.ToNode}";
                            if (path.UsedPath != p)
                            {
                                path.UsedPath = p;
                                _pathService.ReRoutePathEdges(path.PathName);
                            }
                        }
                    }

                }
            }
          
            if (!GlobalValue.IsError)
            {
                _pathService.Synchronous();
            }
        }





        private bool GetTransportFlag()
        {
            bool isCVPM = _asrs.Pcons.Where(x => x.MachineName == "CJVCV400").All(x => x.PconMode == 5);
            bool isSrmDown = _asrs.Srms.FirstOrDefault(x => x.MachineName == "CJSTW200" && x.PortName == "C2")?.DeviceMode == 5;

            bool transportFlag = false;
            // 长巷道堆垛机设宕
            // VCV400切离线触发 VCV300自动切换方向搬送
            var state = _config.GetConfigValue("CJVCV300TRANSPORTSTATE");
            if (isCVPM && isSrmDown)
            {
                transportFlag = true;
                if (state != "1")
                {
                    _config.SetConfigMsg("CJVCV300TRANSPORTSTATE", "1");
                }
            }
            else
            {
                if (state != "0")
                {
                    _config.SetConfigMsg("CJVCV300TRANSPORTSTATE", "0");
                }
                var pcon = _asrs.Pcons.FirstOrDefault(x => x.MachineName == "CJVCV300" && x.PortName == "01");
                if (pcon.WorkType == 2 && !GlobalValue.ErrorFlag1 && !GlobalValue.ErrorFlag2 && !GlobalValue.ErrorFlag3 && !GlobalValue.ErrorFlag4 && !GlobalValue.ErrorFlag5 && !GlobalValue.ErrorFlag6 && !GlobalValue.ErrorFlag7)
                {
                    // 正常情况不为出库模式时自动切换为出库模式
                    InsertMsgQueue(pcon, (ushort)EnumPconSendMsg.ChangeInModeCmd);
                }
            }

            return transportFlag;
        }

        /// <summary>
        /// 自动切换CJVCV400的任务目的地为CJVCV300
        /// </summary>
        private void AutoChangeDestination()
        {
            var vcvTasks = _wcsDbContext.SubTasks
                .Where(x => x.ToLoc == "CJVCV400")
                .Where(x => x.TaskStatus == EnumSubTaskStatus.Ready.ToString()
                    || x.TaskStatus == EnumSubTaskStatus.NewTask.ToString())
                .Include(X => X.MainTask)
                .ToList();
            var vcv400Tasks = _wcsDbContext.SubTasks
                .Where(x => x.FromLoc == "CJVCV400")
                .Where(x => x.TaskStatus == EnumSubTaskStatus.Ready.ToString()
                    || x.TaskStatus == EnumSubTaskStatus.NewTask.ToString())
                .Include(X => X.MainTask)
                .ToList();
            if ((vcvTasks == null || vcvTasks.Count == 0) && (vcv400Tasks == null || vcvTasks.Count == 0))
                return;
            vcvTasks.ForEach(x => 
            {
                x.ToLoc = "CJVCV300";
                x.MainTask.Path = x.MainTask.Path.Replace("CJVCV400", "CJVCV300");
            });
            vcv400Tasks.ForEach(x =>
            {
                x.FromLoc = "CJVCV300";
            });
            _wcsDbContext.UpdateRange(vcvTasks);
            _wcsDbContext.SaveChanges();
        }

        /// <summary>
        /// 自动切换CJVCV300的方向
        /// </summary>
        private void AutoChangeMode()
        {
            // 有货时不切方向
            if (_asrs.Pcons.Where(x => x.MachineName == "CJVCV300").Any(x => x.IsGoods == 1 || !string.IsNullOrEmpty(x.UnitId)))
                return;

            // 有正在去CJVCV300的任务时不切方向
            if (_wcsDbContext.SubTasks.Any(x => x.ToLoc == "CJVCV300" && x.TaskStatus == EnumSubTaskStatus.OnProgress.ToString()))
                return;

            var currentCount = int.Parse(_config.GetConfigValue("CURRENTCJVCV300TRANSPORTCOUNT"));
            var threshold = int.Parse(_config.GetConfigValue("CJVCV300TRANSPORTTHRESHOLD"));
            var pcon = _asrs.Pcons.FirstOrDefault(x => x.MachineName == "CJVCV300" && x.PortName == "01");

            if (currentCount >= threshold)
            {
                var cmd = pcon.WorkType == 1 ? EnumPconSendMsg.ChangeOutModeCmd : EnumPconSendMsg.ChangeInModeCmd;
                InsertMsgQueue(pcon, (ushort)cmd);
                _config.SetConfigMsg("CURRENTCJVCV300TRANSPORTCOUNT", "0");
            }
        }


        /// <summary>
        /// 插入消息队列<br/>
        /// pcon:输送机对象<br/>
        /// cmd :要发送的命令<br/>
        /// </summary>
        private void InsertMsgQueue(PconDto pcon, ushort cmd)
        {
            var deviceMsgQueueDto = new DeviceMsgQueueDto(pcon, new PconSendMsg()
            {
                PconName = (ushort)pcon.PconName,
                Request = cmd
            });
            var deviceMsgQueue = _mapper.Map<DeviceMsgQueue>(deviceMsgQueueDto);
            _wcsDbContext.DeviceMsgQueues.Add(deviceMsgQueue);
        }

        private readonly IPathService _pathService;
        private readonly AutomaticStorageInfo _asrs;
        private readonly IBaseConfigService _config;
        public RouteWorker(IBaseConfigService config, AutomaticStorageInfo asrs, WcsDbContext wcsDbContext, IMapper mapper, ILoggerService logger, IPathService pathService)
            : base(wcsDbContext, mapper, logger)
        {
            _config = config;
            _asrs = asrs;
            _pathService = pathService;
        }
    }
}
